import { useEffect, useReducer } from 'react'
import { get } from '@/utils/request'

// 创建初始状态
const initialState = {
  data: {},
  loading: true,
  error: false,
}

// 定义 action
const FETCH_SUCCESS = 'FETCH_SUCCESS'
const FETCH_ERROR = 'FETCH_ERROR'
const SET_DATA = 'SET_DATA'
const RELOAD_START = 'RELOAD_START'
// 创建 reducer 函数
const reducer = (state, action) => {
  switch (action.type) {
    case FETCH_SUCCESS:
      return {
        ...state,
        loading: false,
        error: false,
        data: action.payload,
      }
    case FETCH_ERROR:
      return {
        ...state,
        loading: false,
        error: true,
      }
    case SET_DATA:
      return {
        ...state,
        data: action.payload,
      }
    case RELOAD_START:
      return {
        ...state,
        loading: true,
        error: false,
      }
    default:
      return state
  }
}

// 自定义 Hooks 获取数据
const useFetchData = (url, params = {}) => {
  // 使用 useReducer 初始化
  const [state, dispatch] = useReducer(reducer, initialState)

  // 获取数据
  const fetchData = async () => {
    try {
      const { data } = await get(url, params)
      dispatch({ type: FETCH_SUCCESS, payload: data })
    } catch (error) {
      dispatch({ type: FETCH_ERROR })
    }
  }

  // 重新获取数据
  const onReload = async () => {
    dispatch({ type: RELOAD_START })
    await fetchData()
  }

  useEffect(() => {
    fetchData()
  }, [url, JSON.stringify(params)])

  return {
    ...state,
    onReload,
  }
}

export default useFetchData
